package com.seckill.util;

import com.seckill.common.model.ValidationResult;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 *
 * @author lill
 * @date 2019-06-24
 */
public class ValidatorUtil {

    /**
     * 快速校验器
     */
    private static Validator validator = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory().getValidator();

    /**
     * 校验
     *
     * @param object
     * @return
     */
    public static ValidationResult validate(Object object) {
        ValidationResult result = new ValidationResult();
        if (null == object) {
            result.setHasErrors(true);
            result.getErrorMsgMap().put(object.getClass().getName(), "请求参数不能为空");
            return result;
        }
        Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(object);
        if (constraintViolationSet.size() > 0) {
            // 有错误
            result.setHasErrors(true);
            constraintViolationSet.forEach(constraintViolation -> {
                String errMsg = constraintViolation.getMessage();
                String propertyName = constraintViolation.getPropertyPath().toString();
                result.getErrorMsgMap().put(propertyName, errMsg);
            });
        }
        System.out.println(object.getClass().getName() + " : " + result.getErrMsg());
        return result;
    }

}


